
//
//  XDLinkPage.m
//  XDEducation
//
//  Created by 星道 on 17/5/17.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDLinkPage.h"

static void(^_Fail)();
static void(^_Success)(NSArray <UIImage *>*);
static NSMutableArray *ImgArr;
/** 获取网络图片 */
@implementation XDLinkPage
+ (void)GetImageArrWithSuc:(void(^)(NSArray <UIImage *>*))Suc Err:(void (^)())Err
{
    _Fail = Err;
    _Success = Suc;
    ImgArr = [NSMutableArray array];
    [self GetImgUrlComplete:^(NSArray<NSString *> *UrlStrArr) {
        [self GetImgData:UrlStrArr Index:0];
    } Fail:nil];
}


+ (void)GetImageURlComplete:(void (^)(NSArray *))Complete Fail:(void (^)())Fail
{
    [self GetImgUrlComplete:^(NSArray *Arr) {
        
        NSString *documentPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject ]stringByAppendingPathComponent:@"path1.txt"];
        [Arr writeToFile:documentPath atomically:YES];
        Complete (Arr);
    } Fail:^{
        Fail ();
    }];
}





#pragma mark - 网络请求结果
+ (void)NetWorkErr
{
    //失败则加载本地引导页
    if (_Fail)
    {
    _Fail ();
    }
}

+ (void)NetWorkSuc
{
    _Success (ImgArr);
}
#pragma mark  End


#pragma mark - 网络请求结果
//获取图片地址
+ (void)GetImgUrlComplete:(void(^)(NSArray <NSString *>*))Complete Fail:(void (^)())Fail
{
    [XDHttpTool get:BaseURL(@"startPicture.do?action=getStartPicture&type=3") success:^(id responseObj) {
        
        if ([responseObj[@"code"] isEqualToNumber:@1000] && [responseObj[@"t"] count] > 0)
        {
            Complete (responseObj[@"t"]);
        }
        else
        {
            [self NetWorkErr];
            if (Fail)
            {
                Fail();
            }
        }
        
    } failure:^(NSError *error) {
        [self NetWorkErr];
        if (Fail)
        {
            Fail();
        }
    }];
    
}

+ (void)GetImgData:(NSArray <NSString *>*)UrlStrArr Index:(NSInteger)Index
{
    if (Index == 0) [ImgArr removeAllObjects];
    
    NSURLSession *Session = [NSURLSession sharedSession];
    NSURLRequest *Request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlStrArr[Index]]];
    NSURLSessionDataTask *dataTask = [Session dataTaskWithRequest:Request completionHandler:^(NSData *  data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error)
        {
            _Fail ();
        }
        else
        {
            UIImage *Image = [UIImage imageWithData:data];

            [ImgArr addObject:Image];
            if (Index == [UrlStrArr count] - 1)
            {
                [self NetWorkSuc];
            }
            else
            {

                [self GetImgData:UrlStrArr Index:(Index+1)];
            }
        }
        
    }];
    [dataTask resume];
}
#pragma mark  End
@end
